function error(txt) {

	var div = document.createElement("div");
	div.innerHTML = txt;
}

var chain = new Array();

var TYPE_SSCOPE = 1;
var TYPE_BLUR = 2;

function AddLink(link) {
	chain.push(link);
}

function WipeChain() {
	chain = new Array();
}

var blendtable = new Array();

for(j = 0; j <= 255; j++) {
	blendtable[j] = new Array();
	for (i = 0; i <= 255; i++) {
		blendtable[j][i] = i / 255 * j;
	}
}

var timer = timer;
var framerate = 20;
var visdata = new Array();
var count = 0;
var width = 32;
var height = 32;
var pixel = 1;
var xscale = 1;
var yscale = 1;
var clearFrame = true;
var bgcolor = 0x000000;
var fgcolor = 0xffffff;
var drawMode = 0;
var line_blend_mode = 2;
var redraw = false;
var count = 0; //debug counter

var buffer = new Array();
var fbout = new Array();

function VisualsReset() {
	width = 32;
	height = 32;
	pixel = 1;
	xscale = 1;
	yscale = 1;
	clearFrame = true;
	bgcolor = 0x000000;
	fgcolor = 0xffffff;
	drawMode = 0;
	line_blend_mode = 2;
	redraw = false;
	count = 0;
	WipeChain();
}

function update() {
	if( clearFrame ) {
		clear();
	}
	var this_thread = 1;
	var max_threads = 1;

	var isBeat = Math.round(Math.random() * 100)
	if (isBeat < 90) 
		isBeat = 0;
	else 
		isBeat = 1;

	var w = width;
	var h = height;
	var s = 0;

	for(var i = 0; i <= 127; i++) { visdata[i] = Math.random(); }

	for(var i = 0; i < chain.length; i++) {
		var t = 0;
		var link = chain[i];
		if(link) {
			var t = link.render(this_thread, max_threads, visdata, isBeat, s?fbout:buffer, s?buffer:fbout, w, h);
			if (t&1) s^=1;	
		} else {
			error("Bad link");
		}
	}

	for(var j = 0; j < buffer.length; j++) {
		BLEND.blend(line_blend_mode, fbout, j, buffer[j]);
	}

	var c_canvas = document.getElementById("canvas");
	var context = c_canvas.getContext("2d");

	buffer_blit(fbout, c_canvas, width, height);

	timer = setTimeout("update()", framerate);
}

function VisualsStop() {
	if(timer) { clearTimeout(timer); timer=null; }
	VisualsReset();
}

function VisualsStart() {
	for(var j = buffer.length; j; j--) {
		buffer[j - 1] = bgcolor;
		fbout[j - 1] = bgcolor;
	}

	timer = setTimeout("update()", 100);
}
function VisualsRestart() {
	VisualsReset();
	VisualsStart();
}
VisualsStop();
